/**
 * @project: parallel-task
 * @package: com.ngplat.paralleltask.utils
 * @filename: ListUtils.java
 *
 * Copyright (c) 2018 eSunny Info. Tech Ltd. All rights reserved.
 * 
 */
package com.ngplat.paralleltask.utils;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @typename: ListUtils
 * @brief: List工具类
 * @author: KI ZCQ
 * @date: 2018年6月4日 下午7:28:13
 * @version: 1.0.0
 * @since
 * 
 */
public class ListUtils {
	
	private static Logger logger = LoggerFactory.getLogger(ListUtils.class);

	/**
	 * 
	 * @Description: 将一个list均分成num个list,主要通过偏移量来实现的
	 * @param source
	 * @param num
	 * @return
	 */
	public static <T> List<List<T>> averageAssign(List<T> source, int num) {
		// 判空处理
		if (source == null || source.size() == 0) {
			return new ArrayList<>();
		}

		// 拆分后的列表集合
		List<List<T>> result = new ArrayList<List<T>>();
		// (先计算出余数)
		int remaider = source.size() % num;
		// 然后是商
		int number = source.size() / num;
		// 偏移量
		int offset = 0;
		// 遍历拆分
		for (int i = 0; i < num; i++) {
			List<T> value = null;
			if (remaider > 0) {
				value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
				remaider--;
				offset++;
			} else {
				value = source.subList(i * number + offset, (i + 1) * number + offset);
			}
			result.add(value);
		}
		return result;
	}

	/**
	 * @Description: 将list按blockSize切分成n多个list 
	 * @param list	源list
	 * @param blockSize	固定大小
	 * @return
	 */
	public static <T> List<List<T>> splitList(List<T> list, int blockSize) {
		List<List<T>> lists = new ArrayList<List<T>>();
		if (blockSize == 1) {
			lists.add(list);
			return lists;
		}
		if (list != null && blockSize > 0) {
			int listSize = list.size();
			if (listSize <= blockSize) {
				lists.add(list);
				return lists;
			}
			int batchSize = listSize / blockSize;
			int remain = listSize % blockSize;
			for (int i = 0; i < batchSize; i++) {
				int fromIndex = i * blockSize;
				int toIndex = fromIndex + blockSize;
				logger.info("[切分子列表-splitList-等分], fromIndex={}, toIndex={}", fromIndex, toIndex);
				lists.add(list.subList(fromIndex, toIndex));
			}
			if (remain > 0) {
				// 最后一个列表的起始索引
				int fromIndex = (listSize - remain);
				logger.info("[切分子列表-splitList-remain], fromIndex={}, toIndex={}", fromIndex, listSize);
				lists.add(list.subList(fromIndex, listSize));
			}
		}
		return lists;
	}

}
